﻿using BCCommon;
using BCEntity.OA.Notification.NotificationCategoryMappingDepartment;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace BCData.OA.Notification.NotificationCategoryMappingDepartment
{
    /// <summary>
    /// OA系统通知分类与部门关系映射
    /// </summary>
	public class NotificationCategoryMappingDepartmentData : INotificationCategoryMappingDepartmentData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM OA_NotificationCategoryMappingDepartment";
        private const string QUERY = @"SELECT NotificationCategoryMappingDepartmentId,CreateTime,NotificationCategoryId,NotificationCategoryCode,NotificationCategoryName,DepartmentId,
		                                    DepartmentName,CompanyId,CompanyName,IsAllJobTitle,AllowJobTitle,
		                                    (
			                                    SELECT GROUP_CONCAT(ItemValue SEPARATOR ',') FROM DictionaryReference WHERE FIND_IN_SET(SearchKey,AllowJobTitle)
		                                    ) AS AllowJobTitleName
                                        FROM OA_NotificationCategoryMappingDepartment";
        public NotificationCategoryMappingDepartmentData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }

        public async Task<bool> Exists(long notificationCategoryMappingDepartmentId)
        {
            string sql = string.Format(@"{0} WHERE NotificationCategoryMappingDepartmentId=?NotificationCategoryMappingDepartmentId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?NotificationCategoryMappingDepartmentId", notificationCategoryMappingDepartmentId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> Exists(string notificationCategoryMappingDepartmentName)
        {
            string sql = string.Format(@"{0} WHERE NotificationCategoryMappingDepartmentName=?NotificationCategoryMappingDepartmentName", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?NotificationCategoryMappingDepartmentName", notificationCategoryMappingDepartmentName, DbType.AnsiString);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<NotificationCategoryMappingDepartmentEntity> Add(NotificationCategoryMappingDepartmentEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("OA_NotificationCategoryMappingDepartment", new string[] { "NotificationCategoryId", "NotificationCategoryCode", "NotificationCategoryName", "DepartmentId", "DepartmentName", "CompanyId", "CompanyName", "IsAllJobTitle", "AllowJobTitle" });
            sql = string.Format("{0} {1} WHERE NotificationCategoryMappingDepartmentId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?NotificationCategoryId", entity.NotificationCategoryId, DbType.Int64);
            parameters.Add("?NotificationCategoryCode", entity.NotificationCategoryCode, DbType.AnsiString, size: 50);
            parameters.Add("?NotificationCategoryName", entity.NotificationCategoryName, DbType.AnsiString);
            parameters.Add("?DepartmentId", entity.DepartmentId, DbType.Int32);
            parameters.Add("?DepartmentName", entity.DepartmentName, DbType.AnsiString);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32);
            parameters.Add("?CompanyName", entity.CompanyName, DbType.AnsiString);
            parameters.Add("?IsAllJobTitle", entity.IsAllJobTitle, DbType.Boolean);
            parameters.Add("?AllowJobTitle", entity.AllowJobTitle, DbType.AnsiString);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<NotificationCategoryMappingDepartmentEntity>(sql, parameters, databaseContext.Transaction);

        }

        public async Task<NotificationCategoryMappingDepartmentEntity> Update(NotificationCategoryMappingDepartmentEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("OA_NotificationCategoryMappingDepartment", new string[] { "NotificationCategoryId", "NotificationCategoryCode", "NotificationCategoryName", "DepartmentId", "DepartmentName", "CompanyId", "CompanyName", "IsAllJobTitle", "AllowJobTitle" }, new string[] { "NotificationCategoryMappingDepartmentId" });
            sql = string.Format("{0} {1} WHERE NotificationCategoryMappingDepartmentId=?NotificationCategoryMappingDepartmentId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?NotificationCategoryMappingDepartmentId", entity.NotificationCategoryMappingDepartmentId, DbType.Int64);
            parameters.Add("?NotificationCategoryId", entity.NotificationCategoryId, DbType.Int64);
            parameters.Add("?NotificationCategoryCode", entity.NotificationCategoryCode, DbType.AnsiString, size: 50);
            parameters.Add("?NotificationCategoryName", entity.NotificationCategoryName, DbType.AnsiString);
            parameters.Add("?DepartmentId", entity.DepartmentId, DbType.Int32);
            parameters.Add("?DepartmentName", entity.DepartmentName, DbType.AnsiString);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32);
            parameters.Add("?CompanyName", entity.CompanyName, DbType.AnsiString);
            parameters.Add("?IsAllJobTitle", entity.IsAllJobTitle, DbType.Boolean);
            parameters.Add("?AllowJobTitle", entity.AllowJobTitle, DbType.AnsiString);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<NotificationCategoryMappingDepartmentEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<bool> Delete(long notificationCategoryMappingDepartmentId)
        {
            string sql = @"DELETE FROM OA_NotificationCategoryMappingDepartment WHERE NotificationCategoryMappingDepartmentId=?NotificationCategoryMappingDepartmentId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?NotificationCategoryMappingDepartmentId", notificationCategoryMappingDepartmentId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters,databaseContext.Transaction) > 0;
        }

        public async Task<NotificationCategoryMappingDepartmentEntity> GetEntity(long notificationCategoryMappingDepartmentId)
        {
            string sql = string.Format(@"{0} WHERE NotificationCategoryMappingDepartmentId=?NotificationCategoryMappingDepartmentId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?NotificationCategoryMappingDepartmentId", notificationCategoryMappingDepartmentId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<NotificationCategoryMappingDepartmentEntity>(sql, parameters);
        }

        public async Task<IEnumerable<NotificationCategoryMappingDepartmentEntity>> GetList()
        {
            return await this.databaseContext.Slave.QueryAsync<NotificationCategoryMappingDepartmentEntity>(QUERY);
        }

        public async Task<(IEnumerable<NotificationCategoryMappingDepartmentEntity>, int)> Query(string notificationCategoryName, DateTime? start, DateTime? end, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (!string.IsNullOrWhiteSpace(notificationCategoryName))
            {
                wheres.Add("NotificationCategoryName LIKE CONCAT('%',CONCAT(?NotificationCategoryName,'%'))");
                parameters.Add("?NotificationCategoryName", notificationCategoryName, DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY CreateTime DESC LIMIT {2},{3}; SELECT COUNT(1) FROM OA_NotificationCategoryMappingDepartment {1}",
                   QUERY,
                   wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                   (pageIndex - 1) * pageSize,
                   pageSize);
            return await this.databaseContext.Slave.QueryMultipleAsync<NotificationCategoryMappingDepartmentEntity,int>(sql, parameters);
        }
    }
}
